<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover" style="border: #ffffff">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商户" prop="mchId">
          <el-select v-model="queryParams.mchId" placeholder="请选择商户" filterable size="small">
            <el-option
              v-for="mch in mchList"
              :key="mch.deptId"
              :label="mch.deptName"
              :value="mch.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入批次名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="tel">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option
              v-for="dict in dict.type.call_notice_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="header_btn">
          <el-button size="small" type="primary" @click="handleQuery">查询</el-button>
          <el-button size="small" @click="resetQuery">重置</el-button>
        </div>
      </el-form>
      <el-card class="box-card" shadow="hover">
        <el-row :gutter="10" class="mb8">
          <right-toolbar style="float: right" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          <el-col :span="1.5" style="float: right;margin-right: 10px">
            <el-button type="warning" plain size="small" @click="handleExport" v-hasPermi="['crm:file:export']">导出</el-button>
          </el-col>

          <el-col :span="1.5" style="float: right">
            <el-button type="danger" plain size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['crm:file:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5" style="float: right">
            <el-button type="success" plain size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['crm:file:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5" style="float: right">
            <el-button type="primary" plain size="small" @click="handleAdd" v-hasPermi="['crm:file:add']">新增</el-button>
          </el-col>
        </el-row>
        <el-table border v-loading="loading" :data="fileList" @selection-change="handleSelectionChange" highlight-current-row>
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="商户" align="center" prop="mchId" width="150" show-overflow-tooltip :formatter="mchPartnerFormat"/>
          <el-table-column label="批次ID" align="center" prop="id"/>
          <el-table-column label="批次名称" align="center" prop="name"/>
          <el-table-column label="批次描述" align="center" prop="description"/>
          <el-table-column label="呼出部门" align="center" prop="trDeptId" :formatter="deptIdFormat"/>
          <el-table-column label="批次状态" align="center" prop="status" :formatter="handleStatus">
            <template slot-scope="scope">
              <el-tag :type="tagType(scope.row.status)">{{handleStatus(scope.row)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="重复数" align="center" prop="repeatCount"/>
          <el-table-column label="导入数" align="center" prop="importCount"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
          <el-table-column label="创建人" align="center" prop="userId" :formatter="userIdFormat" width="180"></el-table-column>
          <el-table-column label="开始/结束" align="center" prop="overTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startTime)}}</span><br/>
              <span>{{ parseTime(scope.row.overTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-tickets"
                @click="handleDetail(scope.row)"
                v-hasPermi="['crm:file:edit']"
              >详情
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['crm:file:edit']">修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['crm:file:remove']"
              >删除
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleStart(scope.row)" v-hasPermi="['crm:file:edit']">启动</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
      </el-card>
    </el-card>
    <!-- 添加或修改语音通知批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="modal_form">
        <el-form-item label="商户" prop="mchId" class="modal_form_item">
          <el-select v-model="form.mchId" filterable placeholder="请选择商户" style="width: 100%">
            <el-option v-for="mch in mchList" :key="mch.deptId" :label="mch.deptName" :value="mch.deptId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="批次名称" prop="name" class="modal_form_item">
          <el-input v-model="form.name" placeholder="请输入批次名称" :disabled="dialogType==='edit'" />
        </el-form-item>
        <el-form-item label="批次描述" prop="description" class="modal_form_item">
          <el-input v-model="form.description" placeholder="请输入批次描述"/>
        </el-form-item>
        <el-form-item label="呼出部门" prop="trDeptId" class="modal_form_item">
          <el-select v-model="form.trDeptId" clearable placeholder="请选择部门" size="small" style="width: 100%">
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId">
              <span style="float: left">{{ dept.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
<!--
        <el-form-item label="呼出部门" prop="trDeptId">
          <el-select v-model="form.trDeptId" placeholder="请选择">
            <el-option
              v-for="item in tokenList"
              :key="item.deptId"
              :label="item.comment"
              :value="item.deptId">
              <span>{{item.comment}}</span>
              <span style="float: right">{{item.deptId}}</span>
            </el-option>
          </el-select>
        </el-form-item>
-->

<!--        <el-form-item label="重复数" prop="repeatCount">
          <el-input v-model="form.repeatCount" placeholder="请输入重复数"/>
        </el-form-item>
        <el-form-item label="导入数" prop="importCount">
          <el-input v-model="form.importCount" placeholder="请输入导入数"/>
        </el-form-item>-->
        <el-form-item label="呼出区间" class="modal_form_item">
          <el-date-picker
            style="width: 100%;"
            v-model="dataTime"
            type="datetimerange"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['12:00:00', '23:00:00']">
          </el-date-picker>
        </el-form-item>
        <div class="tip">
          <small style="font-size: 12px; color: gray;">
            注：号码呼叫时间为开始时间所配置的时分秒值，日期区间内每天只会呼叫一次
          </small>
        </div>

<!--        <el-form-item label="批次开始时间" prop="startTime">
          <el-date-picker
            clearable size="small"
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd"
            placeholder="选择批次开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="批次结束时间" prop="overTime">
          <el-date-picker
            clearable size="small"
            v-model="form.overTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择批次结束时间"
          >
          </el-date-picker>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, delFile, addFile, updateFile, startFile } from '@/api/call/callNotice';
import { allDept } from '@/api/system/dept';
import {getInfo} from '@/api/login'
import { getUserList } from '@/api/system/user';
export default {
  name: 'CallNotice',
  dicts: ['call_notice_status'],
    data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 语音通知批次表格数据
      fileList: [],
      // 部门列表
      deptList: [],
       // 商户
      mchList: [],
      mchOptions:[],
      showRisk: false,
      // 部门ID
      tokenList: [],
       userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        coopid: null,
        fileArchiveUrl: null,
        riskMchId:null,
        deptId: null,
        mchId: null,
      },
      //查询销售
      userParams:{
        deptId:null,
        userId:null,
        status:'0',
        delFlag:'0'
      },
      // 时间
      dataTime: [],
      // 表单参数
      form: {
        trDeptId: null
      },
      // 表单校验
      rules: {
        mchId: [
          { required: true, message: '商户不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '批次名称不能为空', trigger: 'blur' }
        ],
        trDeptId: [
          { required: true, message: '选择拨打部门', trigger: 'blur' }
        ]
      },
      dialogType: "add"
    };
  },
  created() {
    this.getMchList()
    this.getListDepts();

    getInfo().then(
          res => {
            this.getList();
          });
    getUserList(this.userParams).then(response => {
        this.userList = response.data;
      });
  },
  methods: {
    // 启动任务
    handleStart(row){
      if(!row.id) return;
      this.$modal.confirm('是否确认启动语音通知批次"' + row.name + '"的数据项？').then(()=>{
        return startFile(row.id)
      }).then(()=>{
        this.getList();
        this.$modal.msgSuccess('任务启动成功');
      }).catch(() => {
      });
    },
     userIdFormat(row){
      return this.userFormat(row.userId)
    },
    // 人员翻译
    userFormat(id){
      for (const item of this.userList) {
        if (item.dictValue == id) {
          return item.dictLabel;
        }
      }
      return id;
    },
    /** 查询【请填写功能名称】列表 */
    getTokenList() {
      this.loading = true;
      allDept(this.queryParams).then(response => {
        this.tokenList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 标签样式
    tagType(status){
      let styles = ["info","primary","success","danger"];
      return styles[status] || status;
    },
    //状态字典
    handleStatus(row){
      return this.selectDictLabel(this.dict.type.call_notice_status, row.status) || row.status;
    },
     // 格式化商户名称
    mchPartnerFormat(row, column) {
      for (const item of this.mchList) {
        if (item.deptId == row.mchId) {
          return item.deptName;
        }
      }
      return row.mchId;
    },
    //批次详情
    handleDetail(row){
      this.$router.push("/crm/call/callNoticeTel?id="+row.id)
    },
    /** 查询语音通知批次列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dataTime = [];
      this.form = {
        id: null,
        name: null,
        description: null,
        status: 0,
        repeatCount: null,
        importCount: null,
        startTime: null,
        overTime: null,
        createTime: null,
        updateTime: null,
        trDeptId: null,
        mchId: null
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogType = "add";
      this.open = true;
      this.title = '添加语音通知批次';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFile(id).then(response => {
        this.form = response.data;
        this.dataTime=[response.data.startTime || "", response.data.overTime || "",]
        this.dialogType = "edit";
        this.open = true;
        this.title = '修改语音通知批次';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.startTime = "";
      this.form.overTime = "";
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(this.dataTime){
            this.form.startTime = this.dataTime[0];
            this.form.overTime = this.dataTime[1];
          }
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除语音通知批次编号为"' + ids + '"的数据项？').then(function() {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`);
    },
    deptFormat(row){
      let item = this.tokenList.filter(item => {
        return item.deptId === row.trDeptId
      });
      return item[0].comment || row.trDeptId
    },
    /** 获取部门 */
    getListDepts() {
      allDept().then(response => {
        this.deptList = response.data
      })
    },
    /** 部门 */
    deptIdFormat(row, column) {
      for (const item of this.deptList) {
        if (item.deptId == row.trDeptId) {
          return item.deptName;
        }
      }
      return row.trDeptId;
    },
   /** 获取所有的部门 */
       getMchList() {
         allDept().then(response => {
          // 只保留二级部门
          // 如果未来需要根据当前登录人取部门，这个地方需要修改
          for (let item of response.data) {
            if (100 == item.parentId) {
              this.mchList.push(item);
            }
          }
        });
      },
  }
};
</script>
<style lang="scss" scoped>
.app-container{
  //background: #f5f7f9;
  ::v-deep .el-card__header{
    padding: 0;
    line-height: 60px;
  }
  .header_btn{
    margin-top: 3px;
    display: inline-block;
    //float: right;
  }
}
.modal_form {
  .modal_form_item{
    width: 420px;
    display: inline-block
  }
  .modal_form_items{
    width: 470px;
  }
  ::v-deep .el-input__inner {
    font-size: 13px;
  }
  ::v-deep .el-textarea__inner {
    height: 120px;
  }
}
@media screen and (max-width:1480px) {
  ::v-deep .el-dialog{
    left: 130px;
  }
}
</style>
